//
//  ScanDocVModel.swift
//  Scaner
//
//  Created by liyahao on 2025/4/8.
//

import UIKit
import Vision
import Combine
import Foundation

final class ScanDocVModel: ObservableObject {
    
    func cancelOCR() {
        print("cancelOCR")
    }
    
    func resultAction(_ result: CameraResult) {
        switch result {
        case .success(let scan):
            for i in 0..<scan.pageCount {
                self.performOcr(image: scan.imageOfPage(at: i))
            }
        case .failure(let error):
            print(error.localizedDescription)
        }
    }
    
    // 开始OCR
    func performOcr(image: UIImage) {
        guard let cgImage = image.cgImage else { return }
        let requestHandler = VNImageRequestHandler(cgImage: cgImage)
        
        // 创建识别文字请求
        let request = VNRecognizeTextRequest(completionHandler: recognizeTextHandler)
        request.recognitionLevel = .accurate
        request.automaticallyDetectsLanguage = true
        request.revision = VNRecognizeTextRequestRevision3
        request.usesLanguageCorrection = true
        
        print("#OCR: VNRecognizeTextRequestRevision: \(request.revision)")
        
        do {
            // Perform the text-recognition request.
            try requestHandler.perform([request])
        } catch {
            print("Unable to perform the requests: \(error).")
        }
    }
    
    func recognizeTextHandler(request: VNRequest, error: Error?) {
        guard let observations = request.results as? [VNRecognizedTextObservation] else {
            return
        }
        
        let recognizedStrings = observations.compactMap { observation in
            // Return the string of the top VNRecognizedText instance.
            return observation.topCandidates(1).first?.string
        }
        
        print(recognizedStrings)
    }
}
